﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows;

namespace FBApp.Classes
{
    public static class SharedFunctions
    {
        public static BitmapImage loadImage(string ID)
        {
            try
            {
                BitmapImage bi;
                string urlString = "http://graph.facebook.com/" + ID + "/picture";
                if (File.Exists("Resources/Images/cache/" + ID))
                {
                    bi = new BitmapImage(new Uri("Resources/Images/cache/" + ID + ".jpg", UriKind.Relative));
                    double t = bi.Width;
                    return bi;
                }
                else
                {
                    bi = new BitmapImage(new Uri(urlString, UriKind.Absolute));
                    bi.DownloadCompleted += delegate
                    {
                        FileStream stream = new FileStream("Resources/Images/cache/" + ID + ".jpg", FileMode.OpenOrCreate);
                        JpegBitmapEncoder jbe = new JpegBitmapEncoder();
                        jbe.Frames.Add(BitmapFrame.Create(bi));
                        jbe.Save(stream);
                        stream.Flush();
                        stream.Close();
                    };
                    return bi;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading image from cache: " + ex.Message);
            }
            return null;
        }
    }
}
